package com.wangmei.service.serviceimpl;

import com.wangmei.mapper.OrderProductMapper;
import com.wangmei.mapper.OrderdetailMapper;
import com.wangmei.mapper.ProductkuidMapper;
import com.wangmei.model.OrderProduct;
import com.wangmei.model.Orderdetail;
import com.wangmei.model.Productkuid;
import com.wangmei.pojo.*;
import com.wangmei.service.ByCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ByCartServiceImpl implements ByCartService {

    @Autowired
    private OrderdetailMapper orderdetailMapper;

    @Autowired
    private OrderProductMapper orderProductMapper;

    @Autowired
    private ProductkuidMapper productkuidMapper;
    /**
     * 删除单个记录
     * @param key
     * @return
     */
    public int deleteByKey(int key){
        return orderdetailMapper.deleteByPrimaryKey(key);
    }

    /**
     * 批量删除
     * @param keys
     * @return
     */
    public int deleteByKeyList(List keys){
        StringBuilder keyString = new StringBuilder();
        int size = keys.size();
        keyString.append("(");
        for(int i=0 ;i<size;i++){
            if(i != 0)
                keyString.append(",");
            keyString.append(keys.get(i));
        }
        keyString.append(")");
        return orderdetailMapper.deleteByPrimaryKeyString(keyString.toString());
    }

    public int addToCart(int uid, int pid, int num,int kuid, double tprice){
        int flag;
        int oldNum = 0;
        Orderdetail record = new Orderdetail();
        String oid = getOid(uid);
        Map<String,Object> map = new HashMap<>();
        map.put("oid",oid);
        map.put("kuid",kuid);
        List<Orderdetail> list = orderdetailMapper.seletBykuid(map);
        if(list == null || list.size() == 0)
            flag = 1;//插入
        else {
            flag = 0;//修改
            oldNum = list.get(0).getNum();
            record.setDetailid(list.get(0).getDetailid());
        }

        record.setOid(oid);
        record.setNum(num+oldNum);
        record.setPid(pid);
        record.setKuid(kuid);
        record.setTprice(tprice);
        if(flag == 1)
            orderdetailMapper.insertSelective(record);
        else {
            orderdetailMapper.updateByPrimaryKey(record);

        }return 1;
    }

    public BuyCartPojo getBuyCartList(int uid){
        BuyCartPojo pojo = new BuyCartPojo();
        String oid = getOid(uid);
        List<OrderDetailPojo> ods = orderdetailMapper.selectBuyCart(oid);
        int allTotal=0,moneyMoney=0;
        for(OrderDetailPojo od:ods){
            od.setMoneyTotal(od.getPrice()*od.getBuyNum());
            allTotal+=od.getBuyNum();
            moneyMoney+=od.getMoneyTotal();

        }
        pojo.setItems(ods);
        pojo.setAllTotal(allTotal);
        pojo.setMoneyMoney(moneyMoney);

        return pojo;
    }

    @Override
    public int payMoney(String detailids) {
        //添加新的订单，设置
        return 0;
    }

    @Override
    @Transactional
    public String addToPay(OrderDetailPojo[] orderDetailPojos,Map<String,Object> map) {

        //先删除该用户的，state = 1的，否者会。。有bug
        //map 中包含需要的uid 在设置state = 1就够了
        map.put("state",1);
            //查询oid
        List<String> oids = orderProductMapper.queryOrderIdByUid(map);
        if(oids != null && oids.size()>0){
            //存在删除
            Map<String,Object> demap = new HashMap<>();
            StringBuilder deoids =new StringBuilder();
            deoids.append("(");
            for(int i = 0 ;i<oids.size();i++){
                if(i != 0)
                    deoids.append(",");
                deoids.append("'"+oids.get(i)+"'");
            }
            deoids.append(")");
            demap.put("oids",deoids.toString());
            orderProductMapper.deletePay(demap);
            orderdetailMapper.deletePay(demap);
        }
        /**
         * 往order表中插入一条新的记录
         * state = 1//表示支付详细
         * success = 0表示未支付
         */
        String orderid = getOid();
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setOid(orderid);
//        orderProduct.setAddressid((Integer) map.get("addressid"));
        orderProduct.setProductnum(orderDetailPojos.length);
        orderProduct.setOstate(1);
//        Double discount = (Double) map.get("discount");
//        if(discount != null)
//            orderProduct.setDiscount((Double) map.get("discount"));
//        else
//            orderProduct.setDiscount(new Double(1));
//        orderProduct.setPost((Double) map.get("post"));
        orderProduct.setTotal(getTotal(orderDetailPojos));
        String paycode = (String) map.get("paycode");
        if(paycode != null && !"".equals(paycode.trim()))
            orderProduct.setPaycode(paycode);
        orderProduct.setIssuccess(0);
        orderProduct.setUid((Integer) map.get("uid"));
        orderProductMapper.insertSelective(orderProduct);

        //添加order_detail
        StringBuilder value = new StringBuilder();
        int flag = 0;
        for(OrderDetailPojo od :orderDetailPojos){
            if(flag != 0){
                value.append(",");
            }
            value.append("(");
            value.append(od.getPid()+",'"+orderid+"',"+od.getBuyNum()+","+od.getKuid()+","+od.getTprice());
            value.append(")");
            flag++;
        }
        orderdetailMapper.insertValueString(value.toString());
        return orderid;

    }

    /**
     * 立即支付
     * @param orderDetailPojo
     * @return
     */
    @Override
    public int limitToPay(ByAtOnce orderDetailPojo,Map map) {
        //先删除该用户的，state = 1的，否者会。。有bug
        //map 中包含需要的uid 在设置state = 1就够了
        map.put("state",1);
        //查询oid
        List<String> oids = orderProductMapper.queryOrderIdByUid(map);
        if(oids != null && oids.size()>0){
            //存在删除
            Map<String,Object> demap = new HashMap<>();
            StringBuilder deoids =new StringBuilder();
            deoids.append("(");
            for(int i = 0 ;i<oids.size();i++){
                if(i != 0)
                    deoids.append(",");
                deoids.append("'"+oids.get(i)+"'");
            }
            deoids.append(")");
            demap.put("oids",deoids.toString());
            orderProductMapper.deletePay(demap);
            orderdetailMapper.deletePay(demap);
        }

        String orderid = getOid();
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setOid(orderid);
//        orderProduct.setAddressid((Integer) map.get("addressid"));
        orderProduct.setProductnum(1);
        orderProduct.setOstate(1);
        orderProduct.setTotal(orderDetailPojo.getBuyNum()*orderDetailPojo.getPrice()+orderDetailPojo.getTprice());
        orderProduct.setIssuccess(0);
        orderProduct.setUid((Integer) map.get("uid"));
        orderProductMapper.insertSelective(orderProduct);

        Orderdetail record = new Orderdetail();
        record.setTprice(orderDetailPojo.getTprice());
        record.setKuid(orderDetailPojo.getKuid());
        record.setPid(orderDetailPojo.getPid());
        record.setNum(orderDetailPojo.getBuyNum());
        record.setOid(orderid);
        orderdetailMapper.insertSelective(record);
        return 1;
    }
    @Override
    @Transactional
    public int deletebuyCartitem(String detailids, String orderid, int paymethod, List<PayKUID> kuidList) {
        //修改值
        OrderProduct or = orderProductMapper.selectByPrimaryKey(orderid);
        or.setPaymethod(paymethod);
        or.setOstate(2);
        orderProductMapper.updateByPrimaryKey(or);
        //删除值
        orderdetailMapper.deletebyKeys(detailids);
        //修改库存
        for(PayKUID kuid:kuidList){
            int upkuid = kuid.getKuid();
            Productkuid record = productkuidMapper.selectByPrimaryKey(upkuid);
            record.setStorenum(record.getStorenum()-kuid.getNum());
            productkuidMapper.updateByPrimaryKeySelective(record);
        }
        return 0;
    }

    /**
     * 返回orderid ：ostate = 1
     * 产品列表
     * @param uid
     * @return
     */
    @Override
    public Map<String,Object> getBuyCartDetailList(int uid) {
        Map<String,Object> remap = new HashMap<>();

        Map<String,Object> param = new HashMap<>();
        param.put("uid",uid);
        param.put("state",1);
        List<String> oids = orderProductMapper.queryOrderIdByUid(param);
        String oid = null;
        if(oids != null && oids.size()>0)
            oid = oids.get(0);
        param.put("oid",oid);
        List<OrderDetailPojo> reOrderDetal = orderdetailMapper.selectByOid(param);

        remap.put("oid",oid);
        remap.put("OrderDetailPojos",reOrderDetal);
        return remap;
    }

    @Override
    public void readyToPay(Map map) {
        //oid 查询
        OrderProduct record = orderProductMapper.selectByPrimaryKey((String) map.get("oid"));
//        record.setDiscount((Double) map.get("discount"));
//        record.setPost((Double) map.get("post"));
        record.setTotal((Double) map.get("total"));
        record.setPaycode((String) map.get("paycode"));
        record.setAddressid((Integer) map.get("addressid"));
        orderProductMapper.updateByPrimaryKey(record);
    }

    @Override
    public OrderFinish orderfinalsearch(Map<String, Object> map) {
        return orderProductMapper.orderfinalsearch(map);
    }


    private double getTotal(OrderDetailPojo[] orderDetailPojos) {
        BigDecimal total = BigDecimal.ZERO;
        for(OrderDetailPojo od : orderDetailPojos)
            total.add(BigDecimal.valueOf(od.getPrice()*od.getBuyNum()));
        return total.doubleValue();
    }

    private String getOid(int uid){
        Map<String,Object> map = new HashMap<>();
        String oid;
        map.put("uid",uid);
        map.put("state","(0)");
        List<OrderAddr> list = orderProductMapper.queryAllOrder(map);
        //判断是否存在购物车，防止新用户
        if(list == null || list.size() == 0){
            //不存在插入新记录
            oid=getOid();
            OrderProduct record = new OrderProduct();
            record.setOid(oid);
            record.setOstate(0);
            record.setUid(uid);
            orderProductMapper.insert(record);

        }else {
            //存在直接获取oid，添加新记录
            oid = list.get(0).getOid();
        }
        return oid;
    }
    private String getOid(){
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        // 去掉"-"符号
        String time = String.valueOf(System.currentTimeMillis());
        String temp = time+str.substring(0, 3);
        return temp;
    }

}
